<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>json的each</title>
</head>
<body>

</body>
<script src="/static/jquery-3.4.1.js"></script>
<script>

    $(function () {
        eachSimpleArr();
        eachObjArr();
        eachMapArr();
    });

    /**
     * 功能:
     *      jquery遍历简单Array.
     * 输出:
     *      0 1
     *      1 2
     *      2 3
     *      3 4
     * 说明:
     *      1. 可以发现, 在这种情况下, index为下标, value为值.
     */
    function eachSimpleArr() {
        console.log("---each->simpleArr---");
        let data = [1, 2, 3, 4];
        $.each(data, function (index, value) {
            console.log(index, value);
        })
    }

    /**
     * 功能:
     *      jquery遍历对象数组.
     * 输出:
     *      0 {id: 1, name: "s1"}
     *      1 {id: 2, name: "s2"}
     *      2 {id: 3, name: "s3"}
     * 说明:
     *      1. 和遍历普通数组一样, index仍旧是下标, value是值.
     */
    function eachObjArr() {
        console.log("---each->objArr---");
        let data = [{
            id: 1,
            name: "s1"
        }, {
            id: 2,
            name: "s2"
        }, {
            id: 3,
            name: "s3"
        }];
        $.each(data, function (index, value) {
            console.log(index, value);
        })
    }

    /**
     * 功能:
     *      遍历复杂结构.
     * 输出:
     *      0 {1: Array(2), 2: Array(2)}
     *      1 {5: Array(2), 6: Array(2)}
     * 说明:
     *      1. 可以发现, 只要是数组结构, index就一直是下标, value是对应的值.
     */
    function eachMapArr() {
        console.log("---each->complexObjArr---");
        let data = [
            {
                1: [
                    {
                        id: 1,
                        name: "s1"
                    },
                    {
                        id: 2,
                        name: "s2"
                    }
                ],
                2: [
                    {
                        id: 3,
                        name: "s33"
                    },
                    {
                        id: 4,
                        name: "s4"
                    }
                ]
            },
            {
                5: [
                    {
                        id: 5,
                        name: "s5"
                    },
                    {
                        id: 6,
                        name: "s6"
                    }
                ],
                6: [
                    {
                        id: 7,
                        name: "s7"
                    },
                    {
                        id: 8,
                        name: "s8"
                    }
                ]
            }
        ];
        $.each(data, function (index, value) {
            console.log(index, value);
        });
    }

</script>
</html>